# coding=utf-8

import os
import os.path
import shutil
import stat
import sys
from subprocess import Popen, PIPE


# 全局变量

# perforce 和 git 命令执行的工作目录（本地代码库路径）
WORKSPACE_DIR = ''

# perforce 当前工作区
P4_CLIENT=""

# perforce connection info
P4PORT=""
P4USER=""

# MB_DIRS = ['D:', os.sep, 'work', 'dev', 'sync_oglp']
# MB_DIR  = os.path.join(*MB_DIRS)
WORKSPACE_DIR  = r''

def SetPerforcePort(val):
    global P4_PORT
    P4_PORT = val


def SetPerforceUser(val):
    global P4_USER
    P4_USER = val


def SetPerforceClient(val):
    global P4_CLIENT
    P4_CLIENT = val


def SetPerforceDepot(depot):
    global PERFORCE_DEPOT
    PERFORCE_DEPOT = depot


def SetWorkspaceDir(dir):
    global WORKSPACE_DIR
    WORKSPACE_DIR = dir


def ExecCmd(args):
    perforce = Popen(args, stdout = PIPE, stderr = PIPE, cwd = WORKSPACE_DIR, env=None, universal_newlines=True)
    out, err = perforce.communicate()
    print(out)
    if err:
        print(args)
        print(err)
        assert False
    return out, err


def AddGitDiffToP4Change(RevA, RevB, CL_NUM):

    args = ['git', 'diff', '--no-renames', '--name-status', RevA, RevB]
    out, err = ExecCmd(args)

    CMD_MAP = {
        'A' : 'add',
        'M' : 'edit',
        'D' : 'delete',
        # 'R' : None, # 'rename'
    }

    P4_GLOBAL_OPTIONS = ["-c", P4_CLIENT, "-u", P4_USER, "-p", P4_PORT]

    index = 0
    MAX_FILE_SET_SIZE = 32
    MAX_CMD_SIZE = 6000
    CMD_SIZE = 0
    CMD_FOLDER_NAME_SIZE = len(WORKSPACE_DIR) + 2

    lines = out.splitlines()
    # lines = [l for l in lines if l.find('CompileTime') > -1]
    # lines = [l for l in lines if l.find('Competitive') > -1]
    # lines = [l for l in lines if l.find('.xlsx') > -1]
    # lines = [l for l in lines if l.find('Shader_Project') > -1]
    # lines = [l for l in lines if l.find('Shader_Project') > -1]
    # lines = [l for l in lines if not l.find('#') > -1]
    # lines = lines[9298:]

    files = []
    while index < len(lines):

        last_cmd = None

        while index < len(lines):

            line = lines[index]
            cmd = line[0]
            filename = line[1:].strip()
            assert(cmd in CMD_MAP)

            if last_cmd is None:
                last_cmd = cmd
            else:
                if cmd != last_cmd:
                    break

            assert cmd in ('A', 'M', 'D')
            files.append(filename)

            index += 1

            CMD_SIZE += CMD_FOLDER_NAME_SIZE + len(filename)
            if CMD_SIZE > MAX_CMD_SIZE:
                break

        assert last_cmd in ('A', 'M', 'D')
        # file = change[1]
        CL_CMD = ['-c', CL_NUM]
        if last_cmd == 'A':
            CL_CMD.append('-f')

        print("CMD_MAP(CMD) %s %s, File Count = %d" % (CMD_MAP[last_cmd], last_cmd, len(files)))

        args = ['p4', *P4_GLOBAL_OPTIONS, CMD_MAP[last_cmd], *CL_CMD, *[os.path.join(WORKSPACE_DIR, file) for file in files]]
        ExecCmd(args)

        # reset related variables
        files.clear()
        CMD_SIZE = 0


def Main():

    # Check command line argument
    if len(sys.argv)<4:
        print("Usage: %s RevA RevB #CL_NUM" % sys.argv[0])
        exit(-1)

    RevA   = sys.argv[1]
    RevB   = sys.argv[2]
    CL_NUM = sys.argv[3]

    AddGitDiffToP4Change(RevA, RevB, CL_NUM)


if __name__ == "__main__":
    Main()
